package com.spring.security.entity;

import com.google.common.base.MoreObjects;
import com.google.common.collect.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: SysUserRepository
 * Desc:
 * Date： 2017/5/23
 * Created：shaom
 */
//@Entity
public class SysUser implements UserDetails {

//    @Id
//    @GeneratedValue
    private Long id;
    private String username;
    private String password;

//    @ManyToMany(cascade = {CascadeType.PERSIST}, fetch = FetchType.EAGER)
    private List<SysRole> roles;


    /**
     * 授权处理
     * 获取的角色数据
     * 在 SecurityExpressionRoot 中的hasAnyAuthorityName()方法中会获取并判断
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = Lists.newArrayList();
        List<SysRole> roles = getRoles();
        auths.addAll(roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList()));
        return auths;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;//是否过期
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;//账户未锁定为true
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;//证书不过期为true
    }

    @Override
    public boolean isEnabled() {
        return true;//是否可用
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<SysRole> getRoles() {
        return roles;
    }

    public void setRoles(List<SysRole> roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("id", id)
                .add("username", username)
                .add("password", password)
                .add("roles", roles)
                .toString();
    }
}
